﻿using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using RearLivestock.Common.Domains.Enum;
using RearLivestock.Common.Domains.hhx;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using NPOI;
using Microsoft.IdentityModel.Protocols;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.Farrowing
{
    public class ExcelFarrowingsHandler : IRequestHandler<ExcelFarrowingsCommand, FileExportResult>
    {
        /// <summary>
        /// 母猪分娩仓储
        /// </summary>
        private readonly IBaseRepository<Farrowings> farrowingsRepository;
        /// <summary>
        /// 基本信息耳号仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> basicInformationRepository;
        /// <summary>
        /// 栋舍信息仓储
        /// </summary>
        private readonly IBaseRepository<Bedrooms> bedroomsRepository;
        /// <summary>
        ///  栏位仓储
        /// </summary>
        private readonly IBaseRepository<Fields> fieldsRepository;
        /// <summary>
        /// 批次仓储
        /// </summary>
        private readonly IBaseRepository<Batchs> batchsRepository;
        /// <summary>
        /// 分娩难易
        /// </summary>
        private readonly IBaseRepository<Difficulties> difficultiesRepository;
        /// <summary>
        /// 母性
        /// </summary>
        private readonly IBaseRepository<Maternals> maternalsRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="farrowingsRepository"></param>
        /// <param name="basicInformationRepository"></param>
        /// <param name="bedroomsRepository"></param>
        /// <param name="batchsRepository"></param>
        /// <param name="difficultiesRepository"></param>
        /// <param name="maternalsRepository"></param>
        public ExcelFarrowingsHandler(IBaseRepository<Farrowings> farrowingsRepository, IBaseRepository<BasicInformation> basicInformationRepository, IBaseRepository<Bedrooms> bedroomsRepository, IBaseRepository<Fields> fieldsRepository, IBaseRepository<Batchs> batchsRepository, IBaseRepository<Difficulties> difficultiesRepository, IBaseRepository<Maternals> maternalsRepository)
        {
            this.farrowingsRepository = farrowingsRepository;
            this.basicInformationRepository = basicInformationRepository;
            this.bedroomsRepository = bedroomsRepository;
            this.fieldsRepository = fieldsRepository;
            this.batchsRepository = batchsRepository;
            this.difficultiesRepository = difficultiesRepository;
            this.maternalsRepository = maternalsRepository;
        }

        public async Task<FileExportResult> Handle(ExcelFarrowingsCommand request, CancellationToken cancellationToken)
        {
            var result = new FileExportResult();
            //获取母猪分娩列表
            var list = await (from a in await farrowingsRepository.GetAll()
                              join b in await basicInformationRepository.GetAll()
                              on a.BasicInforId equals b.BasicInforId
                              join c in await bedroomsRepository.GetAll()
                              on a.BedroomId equals c.BedroomId
                              join d in await batchsRepository.GetAll()
                              on a.BatchId equals d.BatchId
                              join e in await difficultiesRepository.GetAll()
                              on a.DifficultieId equals e.DifficultieId
                              join f in await maternalsRepository.GetAll()
                              on a.MaternalId equals f.MaternalId
                              join g in await fieldsRepository.GetAll()
                              on a.FieldId equals g.FieldId
                              where a.IsFarrowings == 0
                              select new FarrowingsDto()
                              {
                                  FarrowingId = a.FarrowingId,
                                  BasicInforId = a.BasicInforId,
                                  FarrowingDate = a.FarrowingDate,
                                  GestationNum = a.GestationNum,
                                  DifficultieId = a.DifficultieId,
                                  BatchId = a.BatchId,
                                  MaternalId = a.MaternalId,
                                  Lactation = a.Lactation,
                                  Mastitis = a.Mastitis,
                                  NestNumber = a.NestNumber,
                                  LivePigNum = a.LivePigNum,
                                  NestWeight = a.NestWeight,
                                  Gender = a.Gender,
                                  BedroomId = a.BedroomId,
                                  FieldId = a.FieldId,
                                  TurnBuilding = a.TurnBuilding,
                                  TurnColumn = a.TurnColumn,
                                  IsFarrowings = a.IsFarrowings,
                                  EarNumber = b.EarNumber,
                                  Electronicearlabel = b.Electronicearlabel,
                                  BedroomName = c.BedroomName,
                                  BatchName = d.BatchName,
                                  DifficultieName = e.DifficultieName,
                                  MaternalName = f.MaternalName,
                                  FieldName = g.FieldName,
                              }).ToListAsync();

            // 创建一个新的Excel工作簿
            IWorkbook wb = new XSSFWorkbook();

            // 在工作簿中创建一个新的Sheet
            ISheet sheet = wb.CreateSheet();

            //创建表头,第一行
            IRow row = sheet.CreateRow(0);

            // 设置表头的各个列标题
            row.CreateCell(0).SetCellValue("序号");
            row.CreateCell(2).SetCellValue("耳号");
            row.CreateCell(3).SetCellValue("妊娠天数");
            row.CreateCell(4).SetCellValue("分娩难易");
            row.CreateCell(5).SetCellValue("肥羊批次");
            row.CreateCell(6).SetCellValue("母性");
            row.CreateCell(7).SetCellValue("泌乳");
            row.CreateCell(8).SetCellValue("乳房炎");
            row.CreateCell(9).SetCellValue("窝号");
            row.CreateCell(10).SetCellValue("活猪数");
            row.CreateCell(11).SetCellValue("窝总重(公斤)");
            row.CreateCell(12).SetCellValue("性别");
            row.CreateCell(13).SetCellValue("当前栋舍");
            row.CreateCell(14).SetCellValue("当前栏位");
            row.CreateCell(15).SetCellValue("转入栋舍");
            row.CreateCell(16).SetCellValue("转入栏位");

            // 初始化行索引
            int i = 0;// 注意这里从0行开始 已经是表头了
            foreach (var item in list)
            {
                // 为每条记录创建一行
                row = sheet.CreateRow(i);

                // 填充数据到各列
                row.CreateCell(0).SetCellValue(item.FarrowingId);
                row.CreateCell(2).SetCellValue(item.EarNumber);
                row.CreateCell(3).SetCellValue($"{item.GestationNum}天");
                row.CreateCell(4).SetCellValue(item.DifficultieName);
                row.CreateCell(5).SetCellValue(item.BatchName);
                row.CreateCell(6).SetCellValue(item.MaternalName);
                row.CreateCell(7).SetCellValue(item.Lactation);
                row.CreateCell(8).SetCellValue(item.Mastitis);
                row.CreateCell(9).SetCellValue(item.NestNumber);
                row.CreateCell(10).SetCellValue(item.LivePigNum);
                row.CreateCell(11).SetCellValue(item.NestWeight);
                row.CreateCell(12).SetCellValue(item.Gender);
                row.CreateCell(13).SetCellValue(item.BedroomName);
                row.CreateCell(14).SetCellValue(item.FieldName);
                row.CreateCell(15).SetCellValue(item.TurnBuilding);
                row.CreateCell(16).SetCellValue(item.TurnColumn);

                // 行索引递增
                i++;
            }

            // 将工作簿内容写入字节数组
            byte[] bytes;
            using (MemoryStream ms = new MemoryStream())
            {
                wb.Write(ms);
                bytes = ms.ToArray();
            }

            // 获取.xlsx文件的MIME类型
            string mime = new FileExtensionContentTypeProvider().Mappings[".xlsx"];

            // 设置导出结果对象的属性
            result.FileBytes = bytes;// 文件字节内容
            result.MimeType = mime;// MIME类型
            result.FileName = "订单信息导出.xlsx";// 文件名
            return result;
        }
    }
}
